﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;

namespace PlaneClean.Filter
{
    /// <summary>
    /// 验证注解 传递的数据格式是否正确过滤器
    /// </summary>
    public class AnnotationFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);
            if (!actionContext.ModelState.IsValid)
            {
                foreach (ModelState ms in actionContext.ModelState.Values)
                {
                    if (null == ms.Errors || ms.Errors.Count == 0) continue;
                    if (string.IsNullOrEmpty(ms.Errors[0].ErrorMessage)) continue;
                    if(ms.Errors[0].ErrorMessage== "有一个值是必需的，但请求中不存在该值。") continue;
                    throw new HttpException(400, ms.Errors[0].ErrorMessage);
                }
            }
        }
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
        }
    }
}